1   /*
2    * Copyright (C) 2008 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.testing;
18  
19  import static com.google.common.base.Preconditions.checkNotNull;
20  
21  import com.google.common.annotations.Beta;
22  import com.google.common.annotations.GwtCompatible;
23  
24  import java.util.ArrayList;
25  import java.util.LinkedList;
26  import java.util.List;
27  import java.util.logging.Level;
28  import java.util.logging.Logger;
29  
30  /**
31   * A {@code TearDownStack} contains a stack of {@link TearDown} instances.
32   *
33   * @author Kevin Bourrillion
34   * @since 10.0
35   */
36  @Beta
37  @GwtCompatible
38  public class TearDownStack implements TearDownAccepter {
39    private static final Logger logger = Logger.getLogger(TearDownStack.class.getName());
40  
41    final LinkedList<TearDown> stack = new LinkedList<TearDown>();
42  
43    private final boolean suppressThrows;
44  
45    public TearDownStack() {
46      this.suppressThrows = false;
47    }
48  
49    public TearDownStack(boolean suppressThrows) {
50      this.suppressThrows = suppressThrows;
51    }
52  
53    @Override
54    public final void addTearDown(TearDown tearDown) {
55      stack.addFirst(checkNotNull(tearDown));
56    }
57  
58    /**
59     * Causes teardown to execute.
60     */
61    public final void runTearDown() {
62      List<Throwable> exceptions = new ArrayList<Throwable>();
63      for (TearDown tearDown : stack) {
64        try {
65          tearDown.tearDown();
66        } catch (Throwable t) {
67          if (suppressThrows) {
68            logger.log(Level.INFO, "exception thrown during tearDown", t);
69          } else {
70            exceptions.add(t);
71          }
72        }
73      }
74      stack.clear();
75      if ((!suppressThrows) && (exceptions.size() > 0)) {
76        throw ClusterException.create(exceptions);
77      }
78    }
79  }